package PrjHttpWs

import (
	"errors"
	"io/ioutil"

	"golang.org/x/net/websocket"
)

const (
	WS_MESSAGE_TEXT                = 1
	WS_HTTP_CHANNEL_CMD     string = "/cmd"
	WS_TOPIC_KEY            string = "__topic"
	WS_HTTP_CMD_subscribe          = "subscribe"
	WS_HTTP_CMD_unsubscribe        = "unsubscribe"
	WS_MSG_KEY                     = "__msg"
)

var (
	buf_spliter = []byte{0x0A}
)

func ReceiveMessage(conn *websocket.Conn) (msgtype byte, msg []byte, err error) {
again:
	frame, err := conn.NewFrameReader()
	if err != nil {
		return 0, nil, err
	}
	frame, err = conn.HandleFrame(frame)
	if err != nil {
		return 0, nil, err
	}
	if frame == nil {
		goto again
	}
	maxPayloadBytes := conn.MaxPayloadBytes
	if maxPayloadBytes == 0 {
		maxPayloadBytes = websocket.DefaultMaxPayloadBytes
	}
	payloadType := frame.PayloadType()
	data, err := ioutil.ReadAll(frame)
	if err != nil {
		return 0, nil, err
	}
	return payloadType, data, err
}

func SendWsMessage(conn *websocket.Conn, msgtype byte, msg []byte) error {
	if conn == nil {
		return errors.New("尚未建立连接")
	}
	writer, err := conn.NewFrameWriter(msgtype)
	if err != nil {
		return err
	}
	_, err = writer.Write(msg)
	return err
}

func SendPingMessage(conn *websocket.Conn) error {
	if conn == nil {
		return errors.New("尚未建立连接")
	}
	writer, err := conn.NewFrameWriter(websocket.PingFrame)
	if err != nil {
		return err
	}
	_, err = writer.Write([]byte{})
	return err
}
